package Project1;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.tool.hbm2ddl.SchemaExport;

public class HibernateContext {

	public static AnnotationConfiguration config = null;
	public static SessionFactory factory = null;
	
	/**
	 * sets configuration if null
	 */
	private static void setConfiguration(){
		if(config == null){
			config = new AnnotationConfiguration();
			config.configure();
		}
	}
	
	/**
	 * sets factory if null
	 */
	private static void setFactory(){
		if(factory == null){
			setConfiguration();
			factory = config.buildSessionFactory();
		}
	}

	/**
	 * Opens session from the factory
	 */
	public static Session getSession(){
		setFactory();
		return factory.openSession();
	}
	
	/**
	 * Creates a schema from the configuration
	 */
	public static void createSchema(){
		setConfiguration();
		(new SchemaExport(config)).create(true, true);
		
	}
	
	/**
	 * Adds a new class object to the database
	 */
	public static void addClass(Class c){
		setConfiguration();
		config.addAnnotatedClass(c);
	}
	
	/**
	 * Adds a list of class objects to the database
	 */
	public static void addClasses(Class classes[]){
		for(Class c : classes){
			addClass(c);
		}
	}
}
